package ru.hh.school.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ClientInputHandler extends Thread {
    private final ObjectOutputStream clientEndpointOut;
    private final ObjectInputStream localEndpointIn;
    private final Thread clientChatConsoleThread;

    public ClientInputHandler(ObjectOutputStream clientEndpointOut, InputStream localEndpointIn, Thread clientChatConsoleThread) throws IOException {
        this.clientEndpointOut = clientEndpointOut;
        this.localEndpointIn = new ObjectInputStream(localEndpointIn);
        this.clientChatConsoleThread = clientChatConsoleThread;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                String message = (String) localEndpointIn.readObject();
                synchronized (clientEndpointOut) {
                    clientEndpointOut.writeObject(message);
                }
            }
        } catch (Exception e) {
            Util.ignoredException(e);

        } finally {
            if (clientEndpointOut != null) {
                try {
                    clientEndpointOut.close();
                } catch (IOException e1) {
                    Util.ignoredException(e1);
                }
            }
            if (localEndpointIn != null) {
                try {
                    localEndpointIn.close();
                } catch (IOException e1) {
                    Util.ignoredException(e1);
                }
            }
            clientChatConsoleThread.interrupt();
        }
    }
}
